package com.smarthealthring.mm.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.smarthealthring.mm.R;
import com.smarthealthring.mm.base.BaseActivity;
import com.smarthealthring.mm.constant.ComConstant;
import com.smarthealthring.mm.contract.GetBackPwdContract;
import com.smarthealthring.mm.presenter.GetBackPwdPresenter;
import com.smarthealthring.mm.utils.ComToolBar;
import com.smarthealthring.mm.utils.RandomUtil;
import com.smarthealthring.mm.utils.RegexUtils;
import com.smarthealthring.mm.utils.ToastUtil;
import com.smarthealthring.mm.widgets.CleanEditText;
import com.jakewharton.rxbinding2.view.RxView;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.reactivestreams.Subscription;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * 找回密码 发送验证码
 * Created by bilibili on 2018/5/27.
 */

public class GetBackPwdActivity extends BaseActivity<GetBackPwdPresenter> implements GetBackPwdContract.View{
    @BindView(R.id.tv_get_verifycode)  //获取验证码
    TextView mTvGetVerifyCode;
    @BindView(R.id.tv_phoneno)  //电话号码
    CleanEditText mEtPhoneNo;
    @BindView(R.id.tv_next)  //下一步
    TextView mTvNext;
    @BindView(R.id.et_verifycode) //验证码
    CleanEditText mEtVerifyCode;

    @Override
    protected void initComToolBar() {
        ComToolBar.setTitle(mContext,"找回密码");
        ImageView ivLeft = ComToolBar.setleftImg(mContext, R.drawable.back_white);
        RxView.clicks(ivLeft)
                .subscribe((Consumer) o -> finish());
    }

    @Override
    protected int getLayout() {
        return R.layout.act_getback_pwd;
    }

    @Override
    protected void initEventAndData(@Nullable Bundle savedInstanceState) {
        //获取短信验证码
        RxView.clicks(mTvGetVerifyCode)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        String phoneNo = mEtPhoneNo.getText().toString().trim();

                        if (TextUtils.isEmpty(phoneNo)) {
                            ToastUtil.shortShow("请输入手机号码");
                            return;
                        }
                        if (!RegexUtils.isMobileExact(phoneNo)) {
                            ToastUtil.shortShow("手机号码格式不正确!");
                            return;
                        }
                        mPresenter.getVerifyCode(new HashMap<String, String>() {{
                            put("trans_id", "1001");
                            put("nonce_str", RandomUtil.getRandomString(32));
                            put("mobile", phoneNo);
                            put("vercodetype", ComConstant.MSG_BACK);
                        }});
                        count(); //倒计时
                    }
                });

        //下一步
        RxView.clicks(mTvNext)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        String phoneNo = mEtPhoneNo.getText().toString().trim();
                        //                            String password = mEtPassword.getText().toString().trim();
                        String verifyCode = mEtVerifyCode.getText().toString().trim();
                        if (TextUtils.isEmpty(phoneNo)) {
                            ToastUtil.shortShow("请输入手机号码");
                            return;
                        }
                        if (TextUtils.isEmpty(verifyCode)) {
                            ToastUtil.shortShow("请输入验证码");
                            return;
                        }

                        Intent intent = new Intent(mContext, ResetPwdActivity.class);
                        intent.putExtra("username", phoneNo);
                        intent.putExtra("captchamsg", verifyCode);
                        startActivity(intent);
                    }
                });
    }

    /**
     * 30秒才能发送一次
     */
    private void count() {
        final int time = 60;
        Flowable.interval(0, 1, TimeUnit.SECONDS)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .take(time + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return time - aLong;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Subscription>() {
                    @Override
                    public void accept(Subscription subscription) throws Exception {
                        mTvGetVerifyCode.setEnabled(false);
                    }
                })
                .subscribe(new Consumer<Long>() {
                               @Override
                               public void accept(Long num) throws Exception {
                                   mTvGetVerifyCode.setText("剩余" + num + "秒");

                                   if (num == 0) {
                                       mTvGetVerifyCode.setEnabled(true);
                                       mTvGetVerifyCode.setText("发送验证码");
                                   }
                               }
                           }, throwable -> {

                        }
                        , () -> {
                            mTvGetVerifyCode.setEnabled(true);
                            mTvGetVerifyCode.setText("发送验证码");
                        }
                );
    }

    @Override
    protected GetBackPwdPresenter createPresenter() {
        return new GetBackPwdPresenter();
    }

    @Override
    public void getVerifyCodeSuccess() {

    }

    @Override
    public void getVerifyCodeFail() {

    }
}
